<?php
require_once('config/init.php');
require_once('check.php');

//当前页码
$page = isset($_GET['page']) ? trim($_GET['page']) : 1;

//总条数
$sql = "SELECT COUNT(id) AS c FROM {$pre_}person";
$count = find($sql);
$count = $count['c'];

//每页显示多少条数据
$limit = 6;
$size = 5; //中间显示多少个页码数

//调用分页方法 -> 返回的就是 组装的 html结构
$html = page($page, $count, $limit, $size, 'flickr');
// echo $html;
// exit;

//查询员工列表的数据
$start = ($page - 1)*$limit;
$sql = "SELECT person.*,dep.name AS depname, job.name AS jobname FROM {$pre_}person AS person LEFT JOIN {$pre_}department AS dep ON person.depid = dep.id LEFT JOIN {$pre_}job AS job ON person.jobid = job.id ORDER BY id ASC LIMIT $start,$limit";
// echo $sql;
// exit;

$list = all($sql);

if($_POST)
{
    //返回值
    $success = ['result' => false, 'msg' => ''];

    //接收id
    $list = isset($_POST['list']) ? trim($_POST['list']) : '0';

    //查询出所有删除员工的头像字段
    $sql = "SELECT avatar FROM {$pre_}person WHERE id IN($list) AND avatar IS NOT NULL";
    // echo $sql;
    // exit;

    $avatar = all($sql);

    //想从二维数组中 提取出指定的某一个字段
    $avatar = array_column($avatar, "avatar");

    //先删除数据
    $delnum = del("person", "id IN($list)");

    if($delnum)
    {
        //删除成功
        if(!empty($avatar))
        {
            foreach($avatar as $item)
            {
                // 判断文件是否存在，如果存在就删除 否则不删除
                is_file($item) && @unlink($item);
            }
        }

        $success['result'] = true;
        $success['msg'] = "成功删除了 $delnum 条数据";
    }else
    {
        //删除失败
        $success['result'] = false;
        $success['msg'] = '删除失败';
    }

    //返回json类型 纯输出
    echo json_encode($success);
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?php require_once('meta.php');?>

        <!-- 引入分页样式 -->
        <link rel="stylesheet" href="assets/css/page.css" />
    </head>

    <body>
        <?php require_once('header.php');?>

        <?php require_once('menu.php');?>

        <div class="content">
            <div class="header">
                <h1 class="page-title">员工管理</h1>
            </div>
            <ul class="breadcrumb">
                <li><a href="index.php">Home</a> <span class="divider">/</span></li>
                <li class="active">Index</li>
            </ul>

            <div class="container-fluid">
                <div class="row-fluid">
                    <div class="btn-toolbar">
                        <a class="btn btn-primary" href="PersonAdd.php"><i class="icon-plus"></i> 添加员工</a>
                        <a href="#myModal" onclick="DelAll()" class="btn btn-danger" role="button" data-toggle="modal"><i class="icon-remove"></i> 批量删除</a>
                    </div>
                    <div class="well">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="action"></th>
                                    <th>ID</th>
                                    <th>名称</th>
                                    <th>手机号码</th>
                                    <th>入职时间</th>
                                    <th>所在部门</th>
                                    <th>所在职位</th>
                                    <th style="width: 50px;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($list as $item){?>
                                <tr>
                                    <td><input type="checkbox" name="del[]" value="<?php echo $item['id'];?>" /></td>
                                    <td><?php echo $item['id'];?></td>
                                    <td><?php echo $item['nickname'];?></td>
                                    <td><?php echo $item['mobile'];?></td>
                                    <td><?php echo date("Y-m-d",$item['createtime']);?></td>
                                    <td><?php echo empty($item['depname']) ? "暂无部门" : $item['depname'];?></td>
                                    <td><?php echo empty($item['jobname']) ? "暂无职位" : $item['jobname'];?></td>
                                    <td>
                                        <a href="PersonEdit.php?pid=<?php echo $item['id'];?>"><i class="icon-pencil"></i></a>
                                        <a href="#myModal" onclick="DelOne(this)" data-pid="<?php echo $item['id'];?>" role="button" data-toggle="modal"><i class="icon-remove"></i></a>
                                    </td>
                                </tr>
                                <?php }?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 输出分页 -->
                    <?php echo $html; ?>

                    <!-- modal弹出框 -->
                    <div class="modal small hide fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="myModalLabel">删除提醒</h3>
                        </div>
                        <div class="modal-body">
                            <p class="error-text"><i class="icon-warning-sign modal-icon"></i>是否确认删除</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn" data-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirm">确认</button>
                        </div>
                    </div>

                    <footer>
                        <hr>
                        <p>&copy; 2017 <a href="#" target="_blank">copyright</a></p>
                    </footer> 
                </div>
            </div>
        </div>
    </body>
</html>
<script>
    var list = []

    $("#action").click(function(){
        $("input[name='del[]']").prop("checked", $("#action").prop("checked"))
    })

    //单条删除
    function DelOne(that)
    {
        list = []

        //获取到当前点击的id
        var id = that.dataset.pid

        //判断元素是否在数组中，如果不在在追加
        if(!list.includes(id)) list.push(id)
        
    }

    // 批量删除
    function DelAll()
    {
        list = [] //清空

        //只拿选中的
        $("input[name='del[]']:checked").each((key, element) => {
            if(!list.includes(element.value)) list.push(element.value)
        })
    }

    // 确认方法
    $("#confirm").click(function(){
        if(list.length <= 0)
        {
            alert('请选择删除的选项')
            return false
        }
        
        //发送ajax请求
        $.ajax({
            type: 'post',
            data: {list: list.join(',')},
            dataType: 'json',
            success: success =>
            {
                if(success.result)
                {
                    //删除成功,刷新界面
                    setTimeout(() => location.href = 'PersonList.php', 100)
                }else
                {
                    //删除失败
                    alert(success.msg)
                }
            },
            error: err => 
            {
                console.log(err)
            }
        })
    })
</script>